package com.orange.core.security.handler;

import com.orange.core.util.TokenUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@RequiredArgsConstructor
public class TokenClearingLogoutHandler implements LogoutHandler {

    private final StringRedisTemplate redisTemplate;
    private final String tokenRedisKey;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        if (authentication != null && authentication.isAuthenticated()) {
            String token = TokenUtil.getToken(request);
            Optional.ofNullable(token).ifPresent(t -> redisTemplate.delete(tokenRedisKey + t));

            String username = authentication.getName();
            BoundSetOperations<String, String> setOps = redisTemplate.boundSetOps(tokenRedisKey + username);
            setOps.remove(token);
        }
    }
}
